﻿using HtmlAgilityPack;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace ReaderExtractTool.Service
{
    public class TieShuWangService : BaseService
    {
        public override string GetChapterContent(Chapter chapter, string unnecessaryContentStart)
        {
            String endUrl = chapter.link.Replace("https://www.tiesw.la", "");

            var htmlWeb = new HtmlWeb();
            htmlWeb.OverrideEncoding = Encoding.GetEncoding("gbk");
            var doc = htmlWeb.Load(chapter.link);
            var node = doc.DocumentNode;
            var result = node.SelectNodes("//*[@id='content']");
            string content = result[0].InnerHtml.Replace("\r\n", "").Replace("<p>", "").Replace("</p>", "").Replace("&nbsp;", "").Replace("<br>", "").Replace("&nbs>> --", "")
                                                .Replace("</div>", "")
                                                .Replace("<div><a class=\"btn btn-info\" ", "")
                                                .Replace("</a>", "")
                                                .Replace("href=\"/1_1355/438008_2.html\">", "");
            String matchString = "(第\\d页/共\\d页)";
            content = Regex.Replace(content, matchString, "");
            content = content.Replace("本章未完，点击下一页继续阅读()", "").Replace("\r", "").Replace("\n", "");
            

            if (!string.IsNullOrEmpty(unnecessaryContentStart))
            {
                int index = content.IndexOf(unnecessaryContentStart);
                content = content.Substring(0, index);
            }

            string text = content + "\r\n";

            int pageIndex = 1;
            while (node.InnerHtml.Contains($"_{pageIndex + 1}.html"))
            {
                htmlWeb = new HtmlWeb();
                htmlWeb.OverrideEncoding = Encoding.GetEncoding("gbk");
                doc = htmlWeb.Load(chapter.link.Replace(".html", "") + $"_{++pageIndex}.html");
                node = doc.DocumentNode;
                result = node.SelectNodes("//*[@id='content']");
                content = result[0].InnerHtml.Replace("\r\n", "").Replace("<p>", "").Replace("</p>", "").Replace("&nbsp;", "").Replace("<br>", "").Replace("&nbs>> --", "")
                                                .Replace("</div>", "")
                                                .Replace("<div><a class=\"btn btn-info\" ", "")
                                                .Replace("</a>", "")
                                                .Replace("href=\"/1_1355/438008_" + (pageIndex + 1) + ".html\">", "")
                                                .Replace("<b>> --", " ")
                                                .Replace("</b>", "")
                                                .Replace("p;", "")
                                                .Replace("本章未完，点击下一页继续阅读", "");

                content = Regex.Replace(content, matchString, "");
                content = content.Replace("本章未完，点击下一页继续阅读()", "").Replace("()", "").Replace("\r", "").Replace("\n", "");
                if (!string.IsNullOrEmpty(unnecessaryContentStart))
                {
                    int index = content.IndexOf(unnecessaryContentStart);
                    content = content.Substring(0, index);
                }
                text += content;
            }

            return chapter.name + "\r\n\r\n" + text + "\r\n\r\n";
        }

        public override List<Chapter> GetChapters(string url, ref string novelTitle)
        {
            List<Chapter> chapterList = new List<Chapter>();

            //var doc = new HtmlWeb().Load(url);
            //doc.ov
            //var node = doc.DocumentNode;
            var htmlWeb = new HtmlWeb();
            htmlWeb.OverrideEncoding = Encoding.GetEncoding("gbk");
            var doc = htmlWeb.Load(url);
            var node = doc.DocumentNode;

            string title = node.SelectNodes("html/body/div[3]/div[1]/div/div/div[2]/div[1]/h1").FirstOrDefault()?.InnerText;
            if (!string.IsNullOrEmpty(title) && title.Contains("-"))
            {
                novelTitle = title.Substring(0, title.IndexOf("-"));
            }

            var result = node.SelectNodes("//*[@id='section-list']/li");
            if (result == null || result.Count == 0) throw new Exception("未检测到章节目录");

            // 提取所有章节目录
            foreach (var r in result)
            {
                if (string.IsNullOrEmpty(r.InnerHtml)) continue;

                var chapterNodes = r.ChildNodes.Where(w => w.Name == "a");
                if (chapterNodes == null || chapterNodes.Count() == 0) continue;
                foreach (var chapterNode in chapterNodes)
                {
                    string chapterName = chapterNode.InnerText;
                    string chapterLink = chapterNode.Attributes["href"].Value;
                    chapterList.Add(new Chapter()
                    {
                        name = chapterName,
                        link = url + chapterLink.Split('/').LastOrDefault()
                    });
                }
            }

            int pageIndex = 1;
            while (node.InnerHtml.Contains($"p-{pageIndex + 1}.html#dir"))
            {
                // p-2.html#dir
                doc = new HtmlWeb().Load(url + $"p-{++pageIndex}.html#dir");
                node = doc.DocumentNode;
                result = node.SelectNodes(".//div[@id='list']/ul/li");
                if (result == null || result.Count == 0) throw new Exception("未检测到章节目录");

                // 提取所有章节目录
                foreach (var r in result)
                {
                    if (string.IsNullOrEmpty(r.InnerHtml)) continue;

                    var chapterNodes = r.ChildNodes.Where(w => w.Name == "a");
                    if (chapterNodes == null || chapterNodes.Count() == 0) continue;
                    foreach (var chapterNode in chapterNodes)
                    {
                        string chapterName = chapterNode.InnerText;
                        string chapterLink = chapterNode.Attributes["href"].Value;
                        chapterList.Add(new Chapter()
                        {
                            name = chapterName,
                            link = url + chapterLink.Split('/').LastOrDefault()
                        });
                    }
                }
            }

            return chapterList;
        }
    }
}
